//
//  TextureLoader.m
//  Space
//
//  Created by Norbert Zentai on 2009.10.28..
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "XITextureLoader.h"
//#import <Foundation/Foundation.h>
/*#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>*/

//#import "NSImage+XIExtensions.h"
#import "XIEngine.h"

@implementation XITextureLoader

+ (void)loadTexture:(NSString *)name
{
	XIImage *helpImage=[[XIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]];
#if TARGET_OS_IPHONE
	CGImageRef image = helpImage.CGImage;
#else
	NSData* cocoaData = [NSBitmapImageRep TIFFRepresentationOfImageRepsInArray:[helpImage representations]];
	CFDataRef carbonData = (CFDataRef)cocoaData;
	CGImageSourceRef imageSourceRef = CGImageSourceCreateWithData(carbonData, NULL);
	CGImageRef image = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);
#endif
	CGContextRef texContext;
	GLubyte* bytes = nil;	
	size_t	width, height;
	if (image)
	{
		width = CGImageGetWidth(image);
		height = CGImageGetHeight(image);
		
		bytes = (GLubyte*) calloc(width*height*4, sizeof(GLubyte));
		// Uses the bitmatp creation function provided by the Core Graphics framework. 
		texContext = CGBitmapContextCreate(bytes, width, height, 8, width * 4, CGImageGetColorSpace(image), kCGImageAlphaPremultipliedLast);
		// After you create the context, you can draw the image to the context.
		CGContextDrawImage(texContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), image);
		// You don't need the context at this point, so you need to release it to avoid memory leaks.
		CGContextRelease(texContext);
		
		// setup texture parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bytes);
		free(bytes);
	}
	[helpImage release];
}

/*+ (void)loadTexture:(NSString *)name into:(GLuint *)reference
{
	glBindTexture(GL_TEXTURE_2D, &reference);
	[self loadTexture:name];
}*/

@end